package com.jpro.framework.jackson.serializer;

import cn.hutool.core.util.NumberUtil;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.Date;
import java.util.TimeZone;


// 自定义Date反序列化器
@Slf4j
public  class CustomDateDeserializer extends JsonDeserializer<Date> {
    // 支持的日期格式列表
    private static final String[] DATE_FORMATS = new String[] {
            "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'",
            "yyyy-MM-dd HH:mm:ss",
            "yyyy-MM-dd",
            "yyyy/MM/dd",
            "MM/dd/yyyy"
    };

    @Override
    public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
            throws IOException {
        String dateStr = jsonParser.getText();
        //时间戳类型
        if(NumberUtil.isNumber(dateStr)){
            return  new Date(Long.parseLong(dateStr));
        }
        for (String format : DATE_FORMATS) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat(format);
                // 设置时区（根据实际需求调整）
                sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
                return sdf.parse(dateStr);
            } catch (ParseException e) {
                // 尝试下一种格式
                continue;
            }
        }
        throw new IOException("无法解析日期: " + dateStr + "，支持的格式: " + String.join(", ", DATE_FORMATS));
    }
}